package com.ants.platform.core.interceptor;

import com.alibaba.fastjson.JSON;
import com.ants.platform.core.bean.Request;
import com.ants.platform.core.bean.UserAgent;
import com.ants.platform.core.service.RequestLogService;
import com.ants.platform.core.utils.UserAgentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 将请求信息存储到数据库
 * Created by liushun on 2016/8/22.
 */
public class RequestToDbInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RequestLogService requestLogClient;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userAgent = request.getHeader("user-agent");
        //获取访问客户端信息
        UserAgent client = UserAgentUtil.getUserAgent(userAgent);
        Request req = new Request(String.valueOf(request.getRequestURL())
                , JSON.toJSONString(request.getParameterMap())
                , request.getMethod()
                , request.getRemoteAddr()
                , request.getRequestedSessionId()
                , userAgent
                , client != null ? client.toString() : ""
                , response.getStatus());
        requestLogClient.save(req);
        return true;
    }
}
